import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 周斌
 * Date: 2024-07-05
 * Time: 11:08
 */
public class tcpEchoClient {
    public Socket socket = null;

    public tcpEchoClient(String serverIp,int serverProt) throws IOException {
        socket = new Socket(serverIp,serverProt);
    }
    public void start() throws IOException {
        //打印日志
        System.out.println("客户端启动!");
        //1.从控制台读取
        Scanner scanner = new Scanner(System.in);
        try (InputStream inputStream = socket.getInputStream();
             OutputStream outputStream = socket.getOutputStream()){
            Scanner scannerNetwork = new Scanner(inputStream);
            while(true) {
                System.out.println("请输入你的请求：");
                String request = scanner.next();
                //与服务器规定的规则相对应
                request += "\n";
                //2.发送请求到服务器(写入服务器中)
                outputStream.write(request.getBytes());
                //3.接收从服务器发送过来的响应(从服务器将响应读入客户端)
                if(!scannerNetwork.hasNext()) {
                    break;
                }
                String response = scannerNetwork.next();
                //4.将回应打印到控制台
                System.out.println(response);
            }
        }
    }

    public static void main(String[] args) throws IOException {
        tcpEchoClient client = new tcpEchoClient("127.0.0.1",9999);
        client.start();
    }
}
